<template>
	<div class="article-list" ref="articleList">
		<van-pull-refresh 
			v-model="isLoading" 
			@refresh="onRefresh"
			:success-duration="1500"
		>
		  <van-list
		    v-model="loading"
		    :finished="finished"
		    finished-text="没有更多了"
		    @load="onLoad"
		  >
		    <!-- <van-cell v-for="item in articles" :key="item.art_id" :title="item.title" /> -->
		    <article-item 
				v-for="(item,index) in articles" 
				:key="index" 
				:article="item"
				></article-item>
		  </van-list>
		</van-pull-refresh>
	</div>
</template>

<script>
	import { getArticles } from '@/api/article-list.js'
	import articleItem from '@/components/article-item/article-item.vue'
	export default {
		name: 'ArticleList',
		props:{
			channel:{
				type:Object,
				required:true
			}
		},
		data(){
			return {
				articles:[],
				loading:false,
				finished:false,
				timestamp:null,
				count:0,
				isLoading:false,
				scrollTop:0
				
			}
		},
		components:{
			articleItem
		},
		mounted(){
			const al = this.$refs['articleList']
			// 要做节流
			let flag = false
			al.addEventListener('scroll',()=>{
				if(flag) return 
				flag = true
				setTimeout(()=>{
					this.scrollTop = al.scrollTop
					flag = false
				},100)
			})
		},
		activated(){
			this.$refs['articleList'].scrollTop = this.scrollTop
		},
		methods:{
			async onRefresh(){
				const {data} = await getArticles({
					channel_id:this.channel.id,
					timestamp: Date.now(),
					with_top:1
				})
				const {results} = data.data
				this.articles.unshift(...results)
				this.isLoading = false
				// 4. 提示用户刷新成功
				const message = results.length? `更新了${results.length}条数据`: '暂无数据更新'
				this.$toast(message)
			},
			async onLoad(){
				this.count++
				//channel_id 频道id
				//timestamp 相当于页码 初始为 Date.now()
				//with_top 1|0
				const {data} = await getArticles({
					channel_id:this.channel.id,
					timestamp: this.timestamp || Date.now(),
					with_top:1
				})
				const {results} = data.data
				
				this.articles.push(...results)
				this.loading = false
				if(this.count == 1 | results.length){
					this.timestamp = data.data.pre_timestamp
				}else{
					this.finished = true
				}
			} 
		}
	}
</script>

<style scpoed lang="less">
	.article-list{
		position:fixed;
		top:90px;
		bottom:50px;
		left:0;
		right:0;
		overflow-y:auto;
	}
</style>
